const child_process = require('child_process')

const fs = require('@/utils/fs_promise.js')
const stat = require('@/store/statistics.js')

module.exports = {
    async git_clone(url, path) {
        let gitNotExist = false
        var [err, ret] = await to(fs.access(`${path}/.git`))
        if (err && err.errno === -2) {
            gitNotExist = true
        }

        var [err, ret] = await to(fs.access(path))
        if (!err || err.errno !== -2) {
            if (gitNotExist) {
                return {
                    flag: ERROR.FAILURE,
                    message: `dir(${path}) is exist`,
                }
            } else {
                return {
                    flag: ERROR.OK,
                    message: 'normal',
                }
            }
        }

        var ret = child_process.spawnSync('git', ['clone', url, path], {
            stdio: ['ignore', 'inherit', 'inherit'],
        })

        return {
            flag: ret.status === 0 ? ERROR.OK : ERROR.FAILURE,
            message: `do git clone`,
        }
    },
    async git_status(path) {
        var [err, ret] = await to(fs.access(path))
        if (err && err.errno == -2) {
            return ERROR.NO_ENTRY
        }

        let env = process.env
        env.LANG = 'en_US'
        var ret = child_process.spawnSync('git', ['status'], {
            env,
            cwd: path,
            stdio: ['pipe', 'pipe', 'pipe'],
        })

        let result = ret.stdout.toString()
        let matcher1 = /On branch (\w+)/
        let matcher2 = /Your branch is ([ 0-9A-Za-z_/-]+) with '([^']*)'/
        let branch = matcher1.exec(result)[1]
        let status = matcher2.exec(result)[1]
        let origin = matcher2.exec(result)[2]

        return {
            flag: ret.status === 0 ? ERROR.OK : ERROR.FAILURE,
            message: `${branch} ${status} ${origin}`,
        }
    },
    async git_sync(path) {
        var [err, ret] = await to(fs.access(path))
        if (err && err.errno == -2) {
            return ERROR.NO_ENTRY
        }

        console.log(`git pull --ff-only origin master in '${path}':`)
        var ret = child_process.spawnSync('git', ['pull', '--ff-only', 'origin', 'master'], {
            cwd: path,
            stdio: ['ignore', 'inherit', 'inherit'],
        })

        let flag = ret.status === 0 ? ERROR.OK : ERROR.FAILURE
        return { flag, }
    },
}
